package com.xiaoxx.controller.webSocket;

import com.xiaoxx.common.result.R;
import com.xiaoxx.model.entity.sys.SysUser;
import com.xiaoxx.model.entity.webSocket.OnlineUser;
import com.xiaoxx.model.vo.webSocket.OnlineUserVo;
import com.xiaoxx.server.WebsocketServer;
import com.xiaoxx.service.SysUserService;
import com.xiaoxx.utils.JwtUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author :HX
 * @date : 2023/11/4
 */
@RestController
@Api(value = "OnlienChatController", tags = "websocket实时聊天")
@RequestMapping("/api/onlineChat")
public class OnlienChatController {
    @Autowired
    private WebsocketServer websocketServer;

    @Autowired
    private HttpServletRequest request;
    @Autowired
    private SysUserService sysUserService;

    @ApiOperation("获取在线用户")
    @ApiResponses(value = {@ApiResponse(code = 200, message = "响应成功")})
    @RequestMapping(value = "/getOnlineUserList", method = RequestMethod.GET)
    public R<List<OnlineUserVo>> getOnlineUserList() {
        List<OnlineUser> onlineUserList = websocketServer.getOnlineUserList(JwtUtil.getJwtUser(request).getUserId());
        List<String> userIds = onlineUserList.stream().map(i -> i.getUserId()).collect(Collectors.toList());
        if (userIds.size() <= 0) {
            return R.success(new ArrayList<>());
        }
        List<SysUser> sysUsers = sysUserService.listByIds(userIds);
        List<OnlineUserVo> vos = onlineUserList.stream().map(i -> {
            OnlineUserVo vo = new OnlineUserVo();
            vo.setUserId(i.getUserId());
            vo.setUsername(i.getUsername());
            vo.setCreateTime(i.getCreateTime());
            vo.setHeadPic(i.getHeadPic());
            for (SysUser sysUser : sysUsers) {
                if (sysUser.getId().equals(i.getUserId()) && StringUtils.hasLength(sysUser.getHeadPic())) {
                    vo.setHeadPic(sysUser.getHeadPic());
                }
            }
            return vo;
        }).collect(Collectors.toList());
        return R.success(vos);
    }
}
